#ifndef GSRDEVICE_H
#define GSRDEVICE_H

#include <QObject>
#include <QTimer>
#include <QVector>
#include <QBluetoothDeviceDiscoveryAgent>
#include <QLowEnergyController>
#include <QLowEnergyService>
#include <qmutex.h>
#include "BioSignalDevice.h"

class GSRDevice : public BioSignalDevice {
    Q_OBJECT

signals:
    void newDataReceived(const QVector<double> &data, qint64 timestamp);
    void dataReceived(const QByteArray &data);

public:
    explicit GSRDevice(QObject *parent = nullptr);
    ~GSRDevice();

    // 重写BioSignalDevice虚函数
    bool connect() override;
    bool disconnect() override;
    QString getDeviceInfo() const override;

    // 这两个方法不是覆盖基类的虚函数
    bool isConnected() const { return m_connected; }
    bool isAcquiring() const { return m_acquiring; }

    bool startScanAndConnect();
    bool disconnectDevice();
    void setSampleRate(int rate);       // 设置采样率
    QTimer *m_dataRequestTimer;
    QTimer *m_samplingRateCheckTimer;
    // 添加采样率选项枚举
    enum SamplingRateOption {
        RATE_100HZ = 0,  // 默认100Hz
        RATE_200HZ = 1,  // 200Hz
        RATE_400HZ = 2,  // 400Hz
        RATE_800HZ = 3   // 800Hz
    };

    // 设置采样率的方法
    Q_INVOKABLE bool setSamplingRate(SamplingRateOption rate);

    // 获取当前采样率选项
    SamplingRateOption getCurrentSamplingRateOption() const { return m_samplingRateOption; }

    // 获取所有可用的采样率选项
    static QStringList getAvailableSamplingRates();


public slots:  // 添加公共槽函数声明
    bool startAcquisition() override;  // 将现有方法声明为槽函数
    bool stopAcquisition() override;   // 将现有方法声明为槽函数
    void moveToThread(QThread* thread);
    void requestDataOnce();  // 单次数据请求
    void requestData();
    void startDataCollection();

private slots:
    void onControllerStateChanged(QLowEnergyController::ControllerState state);
    void onServiceDiscovered(const QBluetoothUuid &uuid);
    void onServiceStateChanged(QLowEnergyService::ServiceState state);
    void onCharacteristicChanged(const QLowEnergyCharacteristic &characteristic, const QByteArray &value);
    void onCharacteristicRead(const QLowEnergyCharacteristic &characteristic, const QByteArray &value);
    void onCharacteristicWritten(const QLowEnergyCharacteristic &characteristic, const QByteArray &value);
    void onErrorOccurred(QLowEnergyController::Error error);
    void onServiceError(QLowEnergyService::ServiceError error);
    void onDeviceDiscovered(const QBluetoothDeviceInfo &info);
    void onScanFinished();
    void onScanError(QBluetoothDeviceDiscoveryAgent::Error error);
    void checkSamplingRate();           // 检查采样率
    void scheduleChartUpdate();         // 调度图表更新
    void onDescriptorWritten(const QLowEnergyDescriptor &descriptor, const QByteArray &newValue);

private:
    bool m_dataRequestActive;  // 数据请求活跃状态标志

    // 新增方法声明
    QVector<double> parseDataFrameCorrect(const QByteArray &data);  // 正确的数据解析方法
    int hexToSignedIntPython(const QString &hexStr);  // Python风格的有符号整数转换
    bool m_waitingForWakeupResponse;
    // Qt BLE 相关
    QBluetoothDeviceDiscoveryAgent *m_discoveryAgent;
    QLowEnergyController *m_controller;
    QLowEnergyService *m_uartService;
    QLowEnergyCharacteristic m_txCharacteristic;
    QLowEnergyCharacteristic m_rxCharacteristic;
    QLowEnergyCharacteristic m_statusCharacteristic;

    // 设备信息
    QString m_deviceName;
    QString m_deviceAddress;
    QMap<QString, QBluetoothDeviceInfo> m_discoveredDevices;

    // 状态标志
    bool m_connected;
    bool m_acquiring;
    bool m_scanning;
    bool m_notificationEnabled;          // 通知是否已启用
    bool m_acquisitionStartPending;      // 采集启动是否挂起
    int m_connectionRetryCount;
    const int MAX_CONNECTION_RETRIES = 3;

    // 数据缓冲区
    QVector<QPair<qint64, QByteArray>> m_dataBuffer;
    qint64 m_startTime;
    void debugParseLogic(const QByteArray &data);

    // 定时器
    QTimer *m_connectionTimeoutTimer;
    QTimer *m_scanTimeoutTimer;
    int m_dataRequestInterval;
    int m_samplingRate;

    // 有效帧缓存
    QVector<QMap<QString, QVariant>> m_validFrames;
    QVector<double> parseDataFrame(const QByteArray &data);

    // 工具函数
    int hexToSignedInt(const QString &hexStr);
    void logMessage(const QString &message);
    bool checkBluetoothAvailability();
    void processReceivedData(const QByteArray &data);
    void tryInterpolateFrame(int invalidFrameIdx);
    bool initializeBluetoothBackend();
    bool createControllerForDevice(const QBluetoothDeviceInfo &deviceInfo);
    void startScan();
    void setupController();

    //采样率相关变量
    double m_actualSamplingRate;        // 实际采样率
    qint64 m_lastDataTimestamp;         // 上次数据时间戳
    int m_dataCountSinceLastCheck;      // 数据计数
    QTimer* m_chartUpdateTimer;         // 图表更新定时器
    bool m_chartUpdatePending;          // 图表更新标志

    // 新增：24位有符号整数转换函数
    int hexToSignedInt24(const QString &hexStr);
    int hexToSignedInt16(const QString &hexStr);

    //缓存区写入
    bool tryWriteToBuffer(const QByteArray &data, qint64 timestamp);

    qint64 m_lastRequestTime;  // 跟踪上次请求时间
    int correctSegmentValue(int value, const QString &hexStr);
    void setupThreadConnections();

    QMutex m_dataMutex;  // 保护数据访问的互斥锁
    QThread* m_workerThread; // 工作线程
    QMutex m_bluetoothMutex;

    // 当前采样率选项
    SamplingRateOption m_samplingRateOption;

    // 发送采样率设置命令到设备
    bool sendSamplingRateCommand(SamplingRateOption rate);
};

#endif // GSRDEVICE_H
